<template>
	<view class="home-container">
		<view class="uni-margin-wrap">
			<swiper class="swiper" circular :indicator-dots="true" :autoplay="true" :interval="interval"
				:duration="duration">
				<swiper-item>
					<view class="swiper-item">
						<image src="https://cos.xunmeng.icu/cartoonrabbit/swiper/01.jpeg"></image>
					</view>
				</swiper-item>
				<swiper-item>
					<view class="swiper-item">
						<image src="https://cos.xunmeng.icu/cartoonrabbit/swiper/02.jpeg"></image>
					</view>
				</swiper-item>
				<swiper-item>
					<view class="swiper-item">
						<image src="https://cos.xunmeng.icu/cartoonrabbit/swiper/03.jpeg"></image>
					</view>
				</swiper-item>
				<swiper-item>
					<view class="swiper-item" @tap="toAction()">
						<image src="https://cos.xunmeng.icu/cartoonrabbit/swiper/04.jpeg"></image>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<view class="notice">
			<uni-notice-bar show-icon scrollable text="邀新人, 挣收益, 邀的越多挣得的越多, 红包秒提现." />
		</view>

		<view class="type-container">
			<view class="typebutton" @tap="changeType(1)" :style="'background-color:'+buttonColors[0]">
				<view>
					<view class="yi">清新</view>
				</view>
			</view>
			<view class="typebutton" @tap="changeType(2)" :style="'background-color:'+buttonColors[1]">
				<view>
					<view class="yi">唯美</view>
				</view>
			</view>
			<view class="typebutton" @tap="changeType(3)" :style="'background-color:'+buttonColors[2]">
				<view>
					<view class="yi">古风</view>
				</view>
			</view>
			<view class="typebutton" @tap="changeType(4)" :style="'background-color:'+buttonColors[3]">
				<view>
					<view class="yi">鬼畜</view>
				</view>
			</view>
		</view>

		<view class="create-image-container">
			<view class="description" v-if="!cartoonImageUrl">
				<view>图片制作区域</view>
				<view class="tip">（制作时间一般在1-5分钟）</view>
			</view>
			<view v-else class="image" @tap="viewImage()">
				<image v-if :src="cartoonImageUrl" mode="heightFix"></image>
			</view>
		</view>
		<view class="upLoadImageButton">
			<view @tap="doUpLoadImageToCreat()" class="text" hover-class="chongtext2">
				<image src="../../static/images/other/camera.png"></image>上传图片
			</view>
		</view>
		<view v-if="cartoonImageUrl" class="upLoadImageButton">
			<view @tap="saveImage()" class="text" hover-class="chongtext2">
				<image src="../../static/images/other/save.png"></image>保存图片
			</view>
		</view>
		<view class="huodong" @tap="toAction()">
			<image src="../../static/images/other/action.jpg" mode="widthFix"></image>
		</view>
		<view style="height: 230rpx;"></view>
		<view class="bannerad">
			<ad unit-id="adunit-619582f818cb0d1d" ad-intervals="30"></ad>
		</view>
	</view>
</template>
<script>
	// 引入vuex
	import {
		mapState
	} from 'vuex'
	import {
		baseUrl
	} from '../../utils/http.js'
	export default {
		data() {
			return {
				indicatorDots: true,
				autoplay: true,
				interval: 2000,
				duration: 500,
				cartoonImageUrl: '',
				buttonColors: {
					0: '#f7e4a7',
					1: 'white',
					2: 'white',
					3: 'white'
				},
				createType: 1,
			}
		},
		computed: {
			...mapState('m_user', ['token'])
		},
		onLoad(){
			if(wx.createInterstitialAd){
			      this.interstitialAd = wx.createInterstitialAd({ adUnitId: 'adunit-4a6748356cdd7858' })
			      this.interstitialAd.onLoad(() => {
			        // console.log('onLoad event emit')
					this.interstitialAd.show().catch((err) => {
					  // console.error(err)
					})
			      })
			      this.interstitialAd.onError((err) => {
			        // console.log('onError event emit', err)
			      })
			      this.interstitialAd.onClose((res) => {
			        // console.log('onClose event emit', res)
			      })
			    }
		},
		methods: {
			toAction(){
				uni.navigateTo({
					url:'../../subpkg/earlyclock/index/index'
				})
			},
			changeType(type) {

				if (this.createType == type) {
					return
				}
				for (let i = 0; i < 4; i++) {
					this.buttonColors[i] = 'white'
				}
				this.buttonColors[type - 1] = '#f7e4a7'
				this.createType = type
			},
			doUpLoadImageToCreat() {
				var that = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: res => {
						if (res.tempFiles[0].size > 2 * 1024 * 1024) {
							uni.showToast({
								title: '图片大小超过2M，请重新选择照片',
								icon: 'none'
							})
							return
						}
						uni.showLoading({
							title: '制作中...',
							mask: true
						})
						uni.uploadFile({
							url: baseUrl + '/image/tranforCartoon?type=' + that.createType,
							filePath: res.tempFilePaths[0],
							name: 'imageFile',
							header: {
								Authorization: that.token.data
							},
							success: r => {
								// console.log(r)
								if (r.data) {
									let requit = JSON.parse(r.data)
									if (requit.code && (requit.code == 200)) {
										uni.hideLoading()
										uni.showToast({
											title: '制作成功',
											icon: "success",
											duration: 2000,
											position: 'bottom'
										});
										that.cartoonImageUrl = requit.data.img_url
									} else if (r.statusCode == 401 || r.statusCode == 403 || requit.code == 401 || requit.code == 403) {
										uni.showToast({
											title: '未授权，请登录',
											icon: 'none',
											duration: 2000,
											position: 'bottom',
											complete:res=>{
												uni.removeStorageSync('token')
												uni.removeStorageSync('userInfo')
												uni.redirectTo({
													url: '/subpkg/login/login'
												})
											}
										});
										
									} else {
										uni.hideLoading()
										uni.showToast({
											title: requit.message,
											icon: "none",
											duration: 2000,
											position: 'bottom'
										});
									}
								}
								// uni.hideLoading()
							},
							fail: errr => {
								uni.hideLoading()
								console.log(errr)
							},
							complete() {
								// uni.hideLoading()
							}
						})
					}
				})
			},
			viewImage() {
				let that = this
				uni.previewImage({
					current: 0,
					urls: [that.cartoonImageUrl]
				});
			},
			//获取图片
			doSaveImage(imgSrc) {
				let that = this
				uni.showLoading({
					title: '正在加载',
					mask: true
				});
				uni.downloadFile({
					url: imgSrc,
					success: rr => {
						uni.saveImageToPhotosAlbum({
							filePath: rr.tempFilePath,
							success(res) {
								uni.hideLoading();
								uni.showToast({
									title: '已保存到相册',
									icon: 'success',
									duration: 2000
								})
								setTimeout(() => {
									that.isShow =
										false
								}, 2000)
							},
							fail(err) {
								console.log(err)
								uni.hideLoading();
								uni.showToast({
									title: '已取消保存',
									icon: "error",
									duration: 1500
								});
							}
						})
					},
					fail: ee => {
						// 获取网络图片失败
						uni.hideLoading();
						uni.showToast({
							title: '图片下载失败',
							icon: "error",
							duration: 1500
						});
					}
				})
			},
			async saveImage() {
				let that = this
				uni.getSetting({
					success: res => {
						if (!res.authSetting["scope.writePhotosAlbum"]) {
							//向用户发起授权请求
							uni.authorize({
								scope: "scope.writePhotosAlbum",
								success: () => {
									that.doSaveImage(that.cartoonImageUrl)
								},
								//授权失败
								fail: () => {
									uni.showModal({
										title: "您已拒绝获取相册权限",
										content: "是否进入权限管理，调整授权？",
										success: (res) => {
											if (res.confirm) {
												//调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
												uni.openSetting({
													success: (res) => {
														// console.log(res.authSetting);
													},
												});
											} else if (res.cancel) {
												return uni.showToast({
													icon: "none",
													title: "已取消！",
												});
											}
										},
									});
								}
							})
						} else {
							that.doSaveImage(that.cartoonImageUrl)
						}
					}
				})
			},
		}
	}
</script>
<style>
	page{
		background: #FFFFFF;
	}
</style>
<style lang="scss" scoped>
	.bannerad{
		width: 100%;
		position: fixed;
		bottom: 0;
		/deep/ ad{
			transform: scale(0.8) !important;
		}
	}
	.huodong{
		position: fixed;
		width: 150rpx;
		border-radius: 15%;
		right: 5rpx;
		bottom: 500rpx;
		z-index: 99;
		image{
			width: 100%;
			border-radius: 15%;
		}
	}
	.home-container {
		padding: 0 15rpx;
		position: relative;
	}

	.uni-margin-wrap {
		width: 100%;
		margin-top: 20rpx;
	}

	.swiper {
		height: 300rpx;
	}

	.swiper-item {
		display: block;
		height: 300rpx;
		text-align: center;
		border-radius: 10rpx;
	}

	.swiper-item image {
		height: 100%;
		width: 100%;
		border-radius: 20rpx;
	}

	.uni-bg-red {
		background-color: #007AFF;
	}

	.notice {
		margin: 20rpx 0;

	}

	/deep/.uni-noticebar {
		border-radius: 10rpx !important;
		height: 20rpx;
	}

	.create-image-container {
		height: 400rpx;
		width: 100%;
		background-color: #f7f5d9;
		border-radius: 10rpx;
		border: 1px #007AFF dashed;
		display: flex;
		justify-content: center;
		align-items: center;

		.image {
			height: 100%;
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;

			image {
				height: 100%;
				width: 100%;
			}
		}

		.description {
			font-size: 60rpx;
			font-weight: 900;
			color: #C0C0C0;

			.tip {
				font-size: 30rpx;
				font-weight: 300;
			}
		}
	}

	.type-container {
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		justify-content: center;
		align-items: center;
		flex-wrap: wrap;
		width: 100%;
		height: 90rpx;
		margin-top: 5rpx;
		margin-bottom: 5rpx;
	}

	.typebutton {
		display: flex;
		flex-direction: column;
		justify-content: center;
		height: 90%;
		width: 100rpx;
		text-align: center;
		color: #f2b800;
		margin-left: 50rpx;
		border-radius: 20rpx;
		background-color: #fff;
		border: 1px solid #f2b800;
	}

	.upLoadImageButton {
		width: 100%;
		height: 100rpx;
		margin-top: 10rpx;

		.text {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 260rpx;
			height: 80rpx;
			font-size: 32rpx;
			line-height: 80rpx;
			text-align: center;
			color: white;
			margin: 0 auto;
			border-radius: 2em;
			border: 1px solid #f7f5f5;
			background-color: #3ea2ff;
			box-shadow: inset 2px 2px 2px 0px rgba(255, 255, 255, 0.5),
				7px 7px 20px 0px rgba(0, 0, 0, 0.1), 4px 4px 5px 0px rgba(0, 0, 0, 0.1);

			image {
				height: 40rpx;
				width: 40rpx;
			}
		}
	}
</style>
